//
//  KDSearchResultController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/24.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDSearchResultController.h"
#import "KDSearchHistory.h"
#import "KDSearchRequestTool.h"
#import "KDGetSaerchListParam.h"
#import "KDGetSaerchListResult.h"
#import "KDMKeywordMonitorResult.h"
#import "KDWeiboCell.h"
#import "KDWeibo.h"
#import "KDWeiboCellFrame.h"
#import "KDMListCell.h"
#import "KDMListCellBaseModel.h"
#import "GBSingleWebViewController.h"
#import "KDReportController.h"
#import "KDPatrolgetReportParam.h"
#import "KDMRelationController.h"
#import "UIViewController+BackButtonHandler.h"
#import "KDGetMonitorListParam.h"
#import "KDMBaseBoard.h"
#import "KDSBaseBoard.h"
#import "KDWSBaseBoard.h"
#import "KDMBaseBoardModel.h"
#import "KDProvinceController.h"
@interface KDSearchResultController ()<KDMListCellDelegate,KDWeiboCellDelegate, BackButtonHandlerProtocol, KDMBaseboardDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, copy) NSString * page;

/***  装头部主题的arr */
@property (nonatomic, strong) NSArray *parentThemeArr;
/**
 *  微博数组
 */
@property (nonatomic, strong) NSArray *weiboFrames;
/** 右边弹出的选择界面的遮盖*/
@property (nonatomic, weak) UIButton *cover;
/** 右边弹出的选择界面*/
@property (nonatomic, weak) KDMBaseBoard *baseView;
@property (nonatomic, strong) NSDateFormatter *fmt;
/**
 *  头部scrollView旁边的筛选按钮
 */
@property (nonatomic, weak) UIButton *filterBtn;
/** 当前的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel *baseBoardModel;
/**
 *  没有数据时的提示
 */
@property (nonatomic, weak) UIView * notice;
@end

@implementation KDSearchResultController
#pragma mark - 懒加载区
- (NSArray *)weiboFrames
{
    if (!_weiboFrames) {
        _weiboFrames = [NSArray array];
    }
    return _weiboFrames;
}
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyy-MM-dd";
    }
    return _fmt;
}
- (KDMBaseBoardModel *)baseBoardModel
{
    if (!_baseBoardModel) {//那里找不到了，就自己建
        _baseBoardModel = [[KDMBaseBoardModel alloc]init];
        _baseBoardModel.webSrcType = @"0";
        //        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate:[NSDate date]];
        _baseBoardModel.startTime = @"1970-01-01";//[self.fmt stringFromDate:newdate];
        _baseBoardModel.endTime = @"";
        _baseBoardModel.timeIndex = @"9";
        _baseBoardModel.docType = @"0";
        _baseBoardModel.bussiness = @"0";
        _baseBoardModel.province = 0;
        _baseBoardModel.city = 0;
    }
    return _baseBoardModel;
}
/**
 *  param更新数据
 */
- (void)paramGetData{
//    _param = [[KDGetSaerchListParam alloc]init];
    _param.startTime = self.baseBoardModel.startTime;
    _param.endTime = self.baseBoardModel.endTime;
    _param.property = self.baseBoardModel.docType;
    if (self.param.type) {
        _param.weiboClued = self.baseBoardModel.webSrcType;
         _param.kindType = nil;
    }else{
        _param.kindType = self.baseBoardModel.webSrcType;
    }
    
    _param.province = self.baseBoardModel.province;
    _param.city = self.baseBoardModel.city;
}
/**
 *  将HWStatus模型转为HWStatusFrame模型
 */
- (NSArray *)stausFramesWithWeibos:(NSArray *)weibos
{
    NSMutableArray *frames = [NSMutableArray array];
    for (KDWeibo *weibo in weibos) {
        KDWeiboCellFrame *f = [[KDWeiboCellFrame alloc] init];
//        weibo.version = self.verSion;
        f.weibo = weibo;
        [frames addObject:f];
    }
    return frames;
}
#pragma mark - 板块设置区
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavBar];
    [self setUpTableView];
    [self setUpNoMessageNotice];
    self.notice.hidden = YES;
    self.title = (self.param.type)? @"微博搜索":@"全网搜索";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReportControllerReportSeccess:) name:@"ReportControllerReportSeccessToSearchNoty" object:nil];
}
- (void)setUpNavBar{
//    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"筛选黑"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBtnBtnClick)];
    
    
}
- (void)setUpTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW,  screenH - 40) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorColor = BackGroundColor;
    self.tableView.backgroundColor = BackGroundColor;
    [self.view addSubview:tableView];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];

    //    self.tableView.height -= 100;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    self.tableView.footer = footer;
    [self.tableView.header beginRefreshing];

}
/***  设置没有信息时的提示板*/
- (void)setUpNoMessageNotice{
    UIView * notice = [[UIView alloc]initWithFrame:self.view.bounds];
    notice.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(noticeViewClick)];
    
    [notice addGestureRecognizer:tap];
    self.notice = notice;
    UILabel * noticeLb = [[UILabel alloc]initWithFrame:self.notice.bounds];
    notice.backgroundColor = BackGroundColor;
    notice.y = 0;
    noticeLb.centerY = noticeLb.height * 0.5;
    //    KDLog(@"%@", NSStringFromCGRect(notice.frame));
    noticeLb.text = @"暂时没有满足条件的数据";
    noticeLb.textColor = WQColor(178, 182, 184);
    noticeLb.textAlignment = NSTextAlignmentCenter;
    [notice addSubview:noticeLb];
    [self.view addSubview:notice];

}
/***  设置右边选择页面*/
-(void)setUpRightChoosePage
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!self.cover) {
        //加蒙板
        UIButton *cover = [[UIButton alloc]initWithFrame:window.bounds];
        self.cover = cover;
        cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_cover];
    }
    self.cover.frame = window.bounds;
    //    KDLog/Users/MarkWei/Downloads/办理“深圳市重特大疾病补充医疗保险” 员工个人参保流程操作指引.doc(@"%@", NSStringFromCGRect(self.cover.frame));
    //创建底板
    if (!self.baseView) {
        KDMBaseBoard *baseView;
        if (self.param.type) {
            baseView = [KDSBaseBoard baseboard];
            
        }else{
            baseView = [KDWSBaseBoard baseboard];
            baseView.mainPageType = 5;
        }
        self.baseView = baseView;
        baseView.delegate = self;
        baseView.x = screenW;
        baseView.y = 0;
        //        baseView.height = screenH - baseView.y - 49 ;
        //        baseView.width = screenW - screenW*0.175;
        [_cover addSubview:baseView];
    }
//    self.baseView.outSideKindType = self.selectDetailBtn.tag - 100;
    _baseView.height = screenH - _baseView.y  ;
    _baseView.width = screenW - screenW*0.175;
    [UIView animateWithDuration:0.4 animations:^{
        _baseView.x = screenW*0.175;
    }];
}
#pragma mark - 事件点击区
- (void)backViewClick{
    if (_delegate && [_delegate respondsToSelector:@selector(searchResultCtrlDidPopBack:)]) {
        [_delegate searchResultCtrlDidPopBack:self];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)noticeViewClick{
    [self loadData];
}
/***  筛选按钮被点击 */
- (void)filterBtnBtnClick{
    if (!_filterBtn.selected) {
        //设置右边的选择页面
        [self setUpRightChoosePage];
    } else
    {
        [self coverClick:self.cover];
    }
    _filterBtn.selected = _filterBtn.selected;
}
/***  去掉蒙板及右边页 */
- (void)coverClick:(UIButton *)cover
{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.x = screenW;
    } completion:^(BOOL finished) {
        //        [cover removeFromSuperview];
        self.cover.frame = CGRectZero;
        self.filterBtn.selected = NO;
    }];
    
}
#pragma -mark 网络请求区
- (void)loadData {
    self.notice.hidden = YES;
    if (self.param.type) {
        [self loadWeiboData];
    }else{
        [self loadWebData];
    }
}
- (void)loadMoreData{
    
    if (self.param.type) {
        [self loadMoreWeiboData];
    }else{
        [self loadMoreWebData];
    }
    
}
/**
 *  请求微博数据
 */
- (void)loadWeiboData{
    WS(ws);
    self.page = @"1" ;
//    KDGetSaerchListParam *param = [[KDGetSaerchListParam alloc]init];
    self.param.p = self.page;
    self.param.method = @"weiboSearch";

    [KDSearchRequestTool getSearchListWithParam:self.param WithMainType:self.param.type success:^(KDBaseResult *  responseObejct) {
        KDGetSaerchListResult *result = (KDGetSaerchListResult *)responseObejct;
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
        }else{
            ws.weiboFrames = [self stausFramesWithWeibos:result.info];
            [ws.tableView reloadData];
            [ws.tableView.header endRefreshing];
            [ws.tableView.footer resetNoMoreData];
            if (result.info.count == 0) {
                ws.notice.hidden = NO;
            }else{
                ws.notice.hidden = YES;
                
            }
            
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [ws.tableView.header endRefreshing];
        [ws noticeBadRequest];
    }];
    return;
}
/**
 *  请求全网数据
 */
- (void)loadWebData{
    WS(ws);
    self.page = @"1" ;
//    KDGetSaerchListParam *param = [[KDGetSaerchListParam alloc]init];
    self.param.p = self.page;
    self.param.method = @"networkSearch";
    [KDSearchRequestTool getSearchListWithParam:self.param WithMainType:self.param.type success:^(KDBaseResult * responseObejct) {
        KDMKeywordMonitorResult *result = (KDMKeywordMonitorResult *)responseObejct;
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
        }else{
            ws.weiboFrames = result.info;
            [ws.tableView reloadData];
            [ws.tableView.header endRefreshing];
            [ws.tableView.footer resetNoMoreData];
        if (result.info.count == 0) {
                ws.notice.hidden = NO;
            }else{
                ws.notice.hidden = YES;
                
            }
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [ws noticeBadRequest];
        [ws.tableView.header endRefreshing];
    }];
}
/**
 *  加载更多微博数据
 */
- (void)loadMoreWeiboData{
    WS(ws);
    self.page = [NSString stringWithFormat:@"%ld",self.page.integerValue + 1] ;
    //    KDGetSaerchListParam *param = [[KDGetSaerchListParam alloc]init];
    self.param.p = self.page;
    self.param.method = @"weiboSearch";
    
    [KDSearchRequestTool getSearchListWithParam:self.param WithMainType:self.param.type success:^(KDBaseResult * responseObejct) {
        KDGetSaerchListResult *result = (KDGetSaerchListResult *)responseObejct;
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
        }else{
        NSArray *weiboFrames = [self stausFramesWithWeibos:result.info];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.weiboFrames];
        [arr addObjectsFromArray:weiboFrames];
        self.weiboFrames = arr;
        [ws.tableView reloadData];
        [ws.tableView.footer endRefreshing];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [ws noticeBadRequest];
        [ws.tableView.footer endRefreshing];
    }];

}
- (void)noticeBadRequest{
    UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [messageView show];
}
/**
 *  加载更多全网数据
 */
- (void)loadMoreWebData{
    WS(ws);
    self.page = [NSString stringWithFormat:@"%ld",self.page.integerValue + 1] ;
    self.param.p = self.page;
    self.param.method = @"networkSearch";
    [KDSearchRequestTool getSearchListWithParam:self.param WithMainType:self.param.type success:^(KDBaseResult * responseObejct) {
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
            
        }else{//如果没有更多数据了
            if (responseObejct.count <= ws.weiboFrames.count) {
                [ws.tableView.footer endRefreshing];
                return ;
            }else{
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.weiboFrames];
                [arr addObjectsFromArray:responseObejct.info];
                self.weiboFrames = arr;
                [ws.tableView reloadData];
                [ws.tableView.footer endRefreshing];
            }
        [ws.tableView reloadData];
        [ws.tableView.footer endRefreshing];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [ws noticeBadRequest];

        [ws.tableView.footer endRefreshing];
    }];
}
#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.weiboFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.param.type) {
        KDWeiboCell *cell = [KDWeiboCell cellWithTableView:tableView andVersion:self.verSion];
        
        cell.delegate = self;
        cell.weiboCellFrame = self.weiboFrames[indexPath.row];
//        cell.version = self.verSion;
        return cell;
    }else{
        KDMListCell *cell = [KDMListCell cellWithTableView:tableView andVersion:self.verSion];
        cell.model = self.weiboFrames[indexPath.row];
        cell.delegate = self;
        return cell;
    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.param.type) {
        KDWeiboCellFrame *frame = self.weiboFrames[indexPath.row];
        return frame.cellHeight ;
    }else{
        return 120;
    }

}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.param.type) {
        
    }else{
        KDMListCellBaseModel *model = self.weiboFrames[indexPath.row];
//        KDMListCell *cell = (KDMListCell *)[tableView cellForRowAtIndexPath:indexPath];
//        cell.highlight = YES;
        GBSingleWebViewController *singleCtrl = [[GBSingleWebViewController alloc]init];
        singleCtrl.docid = model.docId;
        singleCtrl.titleee = model.title;
        singleCtrl.isCollect = model.isSave;
        singleCtrl.keyword = model.keywords;
        singleCtrl.whichPage = [NSString stringWithFormat:@"%ld",(long)indexPath.row] ;
        singleCtrl.url = model.url;
        singleCtrl.comeFrom = @"5";
        singleCtrl.report = model.isReport;
        singleCtrl.ori_content = model.content;
        singleCtrl.st = model.date;
        singleCtrl.ori_author = model.author;
        singleCtrl.ori_webname = model.source;
        KDMListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.highlight = YES;
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:singleCtrl animated:YES];
    }
    
}
#pragma mark - KDMListCellDelegate
- (void)KDMListCell:(KDMListCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDMListCellBaseModel *model = cell.model;
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.ori_url = model.url;
    param.ori_title = model.title;
    param.ori_content = model.content;
    param.st = model.date;
    param.doc_id = model.docId;
    if (model.author.length == 0) {
        param.ori_author = nil;
    }else{
        param.ori_author = model.author;
    }
    param.ori_webname = model.source;
    reportCtrl.param = param;
    reportCtrl.type = 3;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:reportCtrl animated:YES];
}

- (void)KDMListCell:(KDMListCell *)cell relationBtnClick:(UIButton *)relationBtn{
    KDMRelationController *relation = [[KDMRelationController alloc]init];
    KDGetMonitorListParam *param = [[KDGetMonitorListParam alloc]init];
    param.topicId = cell.model.topicId;
    relation.param = param;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:relation animated:YES];
}

- (void)KDMListCell:(KDMListCell *)cell collectBtnClick:(UIButton *)collectBtn{
    NSIndexPath *ip = [self.tableView indexPathForCell:cell];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.weiboFrames];
    [arr replaceObjectAtIndex:ip.row withObject:cell.model];
    self.weiboFrames = arr;
}

#pragma mark - KDWeiboCellDelegate
/**
 *  微博界面的上报按钮被点击了
 */
- (void)reportBtnClickWithCell:(KDWeiboCell *)cell{
    KDWeibo *model = cell.weiboCellFrame.weibo;
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.ori_url = @"";
    param.ori_title = model.text;
    param.ori_content = model.text;
    param.st = model.date;
    param.doc_id = model.ID;
    if (model.uname.length == 0) {
        param.ori_author = nil;
    }else{
        param.ori_author = model.uname;
    }
    param.ori_webname = @"新浪微博";
    reportCtrl.param = param;
    reportCtrl.type = 3;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:reportCtrl animated:YES];
    
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
                break;
            default:
                break;
        }
    }
    
}
#pragma mark - BackButtonHandlerProtocol
- (BOOL)navigationShouldPopOnBackButton{
    if (_delegate &&[_delegate respondsToSelector:@selector(searchResultCtrlDidPopBack:)]) {
        [_delegate searchResultCtrlDidPopBack:self];
    }
    return YES;
}

#pragma mark - 通知接收区
- (void)ReportControllerReportSeccess:(NSNotification *)noty{
    NSString *docid = noty.userInfo[@"docid"];
    int i = 0;
    for (id model1 in self.weiboFrames) {
        if (self.param.type) {//微博的
            KDWeiboCellFrame *model = model1;
            if ([docid isEqualToString: model.weibo.ID]) {
                
                model.weibo.isreport = YES;
                NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.weiboFrames];
                [tempArr replaceObjectAtIndex:i withObject:model];
                self.weiboFrames = tempArr;
                NSIndexPath *ip = [NSIndexPath indexPathForRow:i inSection:0];
                KDWeiboCell *cell = [self.tableView cellForRowAtIndexPath:ip];
                cell.weiboCellFrame = model;
                return;
            }
            i++;
        }
        
    }
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - KDSBaseboardDelegate
/**
 *  侧边栏确定按钮被点击了
 */
- (void)baseBoard:(KDSBaseBoard *)baseBoard confirmBtnDidClickWithBaseBoardModel:(KDMBaseBoardModel *)model{
//    self.notice.hidden = YES;
    self.baseBoardModel = model;
    if (self.param) {
    }
    [self paramGetData];
    [self.tableView.header beginRefreshing];
    [self coverClick:self.cover];
}
/**
 *  侧边栏地区选择按钮被点击了
 */
- (void)areaBtnClickWithBaseBoard:(KDMBaseBoard *)baseBoard{
    KDProvinceController *vc = [[KDProvinceController alloc]init];
    vc.fromWeibo = YES;
    self.here = YES;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
/**
 *  侧边栏的类型按钮被点击了
 */
//- (void)kindTypeBtnClickWithBtnTag:(NSInteger)tag{
//    UIButton *btn = (UIButton *)[self.detailScrollView viewWithTag:tag +100];
//    self.selectDetailBtn = btn;
//}
@end
